import Vue from "vue";
import VueRouter from "vue-router";
import NProgress from "nprogress";
import { Message } from "element-ui";
import { getCookie } from "xingyuelongchen";
import store from "@/store";
import menu from "./menu";
Vue.use(VueRouter);
const staticRoutes = [
  {
    path: "/404",
    name: '404',
    component: () => import("@/layout/404"),
    meta: { title: "未找到资源！" }
  },
  {
    path: "/login",
    name: 'login',
    component: () => import("@/views/login"),
    meta: { title: "登陆" }
  },
  { path: '*', redirect: '/404' }
];
const createRouter = () => {
  return new VueRouter({
    // mode: "history",
    base: process.env.BASE_URL,
    routes: [{ path: "/", redirect: "/login" }, ...staticRoutes]
  });
}
const router = createRouter();
let token = getCookie('token');
if (token) addRouter();
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher
}
export function addRouter() {
  resetRouter();
  let route = menu;
  let routes = [
    {
      path: "/",
      component: () => import("@/layout"),
      meta: { isAuth: true, title: '首页' },
      children: route
    },
  ];
  router.addRoutes(routes);
  store.commit('setRoutes', route);
  let timer = setTimeout(() => {
    router.replace(route[0]);
    clearTimeout(timer);
  }, 200)
}

router.beforeEach((to, from, next) => {
  NProgress.start()
  let token = getCookie('token');
  if (to.matched.some(e => e.meta.isAuth) && !token) {
    Message.error('未登录');
    next("/login");
    return;
  }
  next();
});
router.afterEach((to, form) => {
  NProgress.done()
});
export default router
